package com.example.jin.myapplication;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;

import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.design.widget.TextInputEditText;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.ImageView;

import java.io.File;
import java.util.Date;
import java.util.UUID;

/**
 * Created by jin on 2016/5/30.
 */
public class CrimeFragment extends Fragment{
    private TextInputEditText mEditText;
    private Button  mButton;
    private CheckBox mCheckBox;
    private ImageView mImageView;
    private ImageButton mImageButton;
    private Crime mCrime=null;
    private File mImageFile;
    private Callback mCallback;
    public interface Callback{
        void onItemUpdate(Crime c);
    }
    public static Fragment build(UUID id)
    {
        Fragment fragment=null;
        Bundle bundle=new Bundle();
        bundle.putSerializable("crimeid",id);
        fragment=new CrimeFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mCallback=(Callback)context;
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mCallback=null;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        UUID crimeid=(UUID)getArguments().getSerializable("crimeid");
        if(crimeid!=null)
            mCrime=CrimeList.Instance(getActivity()).getCrime(crimeid);

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Log.i("main","CrimeFragment.onCreateView");
        View view=inflater.inflate(R.layout.fragment_crimedetail,container,false);
        mImageView=(ImageView)view.findViewById(R.id.imageview);
        mImageButton=(ImageButton)view.findViewById(R.id.imagebutton);
        mImageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent();
                intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
                mImageFile=CrimeList.Instance(getActivity()).getPhotoFile(mCrime);
                Log.i("main","Uri:"+Uri.fromFile(mImageFile));
                intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(mImageFile));
                startActivityForResult(intent,0x58);
            }
        });
        mEditText=(TextInputEditText)view.findViewById(R.id.textinputedittext_title);
        mButton=(Button)view.findViewById(R.id.button);
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FragmentManager manager=getActivity().getSupportFragmentManager();
                Log.i("main",mCrime.getDate().toString());
                DatePickerFragment fragment=DatePickerFragment.Instance(mCrime.getDate());
                //Fragment和Fragment之间数据通信（灵活）
                fragment.setTargetFragment(CrimeFragment.this,DatePickerFragment.REQUEST_CODE);
                fragment.show(manager,"datepickerfragment");
            }
        });
        ((Button)view.findViewById(R.id.button1)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent=new Intent();
                intent.setAction(Intent.ACTION_SEND);
                intent.setType("text/plain");
                intent.putExtra(Intent.EXTRA_TEXT,"CrimeReport");
                intent.putExtra(Intent.EXTRA_SUBJECT,"subject");
                intent=Intent.createChooser(intent,"Select");
                if(getActivity().getPackageManager().resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY)==null)
                    startActivity(intent);
            }
        });
        ((Button)view.findViewById(R.id.button2)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent();
                intent.setAction(Intent.ACTION_PICK);
                intent.setData(ContactsContract.Contacts.CONTENT_URI);
                intent=Intent.createChooser(intent,"Select");
                startActivityForResult(intent,0x56);
            }
        });

        mCheckBox=(CheckBox)view.findViewById(R.id.checkbox_solved);

        if(mCrime!=null){
            mEditText.setText(mCrime.getTitle());
            mEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    if(hasFocus==false){
                        mCrime.setTitle(mEditText.getText().toString());
                        if(mCallback!=null){
                            mCallback.onItemUpdate(mCrime);
                        }
                    }
                }
            });
            mButton.setText(mCrime.getDate().toString());
            mCheckBox.setChecked(mCrime.isSolved());
            mCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    mCrime.setSolved(isChecked);
                    if(mCallback!=null){
                        mCallback.onItemUpdate(mCrime);
                    }
                }
            });
        }
        getActivity().setResult(0,null);
        return view;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode==DatePickerFragment.REQUEST_CODE){
            Log.i("main","onActivityResult");
            Date date=(Date)data.getSerializableExtra("date");
            mButton.setText(date.toString());
            mCrime.setDate(date);
            if(mCallback!=null){
                mCallback.onItemUpdate(mCrime);
            }
        }
        else if(requestCode==0x58){
            if(mImageFile==null)
                return;
            if(resultCode!= Activity.RESULT_OK){
                Log.i("main","Not OK");
            }

            Log.i("main","exists:"+mImageFile.exists());
            Bitmap bitmap=PictureUtils.getScaledBitmap(mImageFile.getPath(),300,300);
            if(bitmap!=null)
            mImageView.setImageBitmap(bitmap);
        }
        else if(requestCode==0x56){
            Uri contactUri=data.getData();
            String[] queryFields=new String[]{
                    ContactsContract.Contacts.DISPLAY_NAME
            };
            Cursor c = getActivity().getContentResolver()
                    .query(contactUri, queryFields, null, null, null);
            try {
                if (c.moveToNext()) {
                    Log.i("main", "Suspect:" + c.getString(0));
                }
            }
            finally {
                c.close();
            }
        }
    }

    //保存
    @Override
    public void onPause() {
        super.onPause();
        mCrime.setTitle(mEditText.getText().toString());
        mCrime.setSolved(mCheckBox.isChecked());
        CrimeList.Instance(getActivity()).updateCrime(mCrime);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //对于UI的恢复很有用，与SetRetain的区别
    }
}
